﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using RoketSolutions.SP2010.Infrostructure.UI.Controls;
using RoketSolutions.SP2010.Infrostructure.UI.Controls.Interfaces;
using RoketSolutions.SP2010.SecurityTrimming.SecurityTrimming;
using RoketSolutions.SP2010.SecurityTrimming.WebControls;
using System.Linq;
using RoketSolutions.SP2010.SecurityTrimming.Extenstions;

namespace SecurityTrimming.WebParts.SecurityTrimming
{
    public partial class SecurityTrimmingToolPartControl : UserControlBase, ISecurityTrimmingControl, IToolPartControl<TrimmingSettings>
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsInitPhase)
            {
                BindData();
            }
        }

        #region / Properties /

        public Control Control
        {
            get { return this; }
        }

        TrimmingSettings _settings;
        public TrimmingSettings Settings
        {
            get { return _settings ?? (_settings = ViewState["TrimmingSettings"] as TrimmingSettings); }
            set { ViewState["TrimmingSettings"] = _settings = value; }
        }

        private bool IsInitPhase { get; set; }

        #endregion

        #region / Methods /

        public void Initialize(TrimmingSettings settings)
        {
            if (Settings == null)
            {
                Settings = settings;
                IsInitPhase = true;
            }
        }

        public TrimmingSettings SaveData()
        {
            SaveAccountSettings(Settings);
            Settings.UseTrimmingProvider = CheckBoxUseTrimmingProvider.Checked;
            return Settings;
        }

        private void BindData()
        {
            CheckBoxUseTrimmingProvider.Checked = Settings.UseTrimmingProvider;

            RepeaterSettings.DataSource = Settings;
            RepeaterSettings.DataBind();
        }

        private void SaveAccountSettings(TrimmingSettings settings)
        {
            foreach (RepeaterItem repeaterItem in RepeaterSettings.Items)
            {
                if (repeaterItem.ItemType == ListItemType.Item || repeaterItem.ItemType == ListItemType.AlternatingItem)
                {
                    var hdnControlId = repeaterItem.FindControl("HiddenControlId") as HiddenField;
                    var peAlloAccounts = repeaterItem.FindControl("PeopleEditorAllowAccounts") as PeopleEditor;
                    var peDenyAccounts = repeaterItem.FindControl("PeopleEditorDenyAccounts") as PeopleEditor;

                    var settingDefinition = settings[hdnControlId.Value];
                    if (settingDefinition != null)
                    {
                        settingDefinition.AllowAccounts.Clear();
                        settingDefinition.AllowAccounts.AddRange(ResolveAccounts(peAlloAccounts));

                        settingDefinition.DenyAccounts.Clear();
                        settingDefinition.DenyAccounts.AddRange(ResolveAccounts(peDenyAccounts));
                    }
                }
            }
        }

        private IEnumerable<AccountEntity> ResolveAccounts(PeopleEditor peopleEditor)
        {
            var result = new List<AccountEntity>();

            result.AddRange(
                from entity in peopleEditor.ResolvedEntities.Cast<PickerEntity>()
                select new AccountEntity
                           {
                               AccountName = entity.Key,
                               AccountType = entity.GetAccountType()
                           }
                );

            return result;
        }

        #endregion

        #region / Controls Event Handlers /

        protected void OnRepeaterSettingsItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var dataItem = e.Item.DataItem as SettingDefinition;
            if (dataItem != null)
            {
                var lblControlId = e.Item.FindControl("LabelControlControlId") as Label;
                var ltlControlTitle = e.Item.FindControl("LiteralControlTitle") as Literal;
                var hdnControlId = e.Item.FindControl("HiddenControlId") as HiddenField;
                var peAlloAccounts = e.Item.FindControl("PeopleEditorAllowAccounts") as PeopleEditor;
                var peDenyAccounts = e.Item.FindControl("PeopleEditorDenyAccounts") as PeopleEditor;

                lblControlId.Attributes["targetcontrolid"] = EscapeClientId(dataItem.ControlId);
                ltlControlTitle.Text = dataItem.ControlTitle;
                hdnControlId.Value = dataItem.ControlId;

                BindPeopleEditor(peAlloAccounts, dataItem.AllowAccounts.Select(account=>account.AccountName).ToArray());
                BindPeopleEditor(peDenyAccounts, dataItem.DenyAccounts.Select(account=>account.AccountName).ToArray());
            }
        }

        private string EscapeClientId(string controlClientId)
        {
            return !controlClientId.Contains("g_")
                       ? controlClientId
                       : controlClientId.Substring(controlClientId.LastIndexOf("g_") + 2).Replace("_", "-");
        }

        #endregion

    }
}
